#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
插入100条测试数据到tasks表
"""

import os
import sys
import django
from datetime import datetime, timedelta
import random

# 添加项目根目录到Python路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

# 设置Django环境变量
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'dev07.settings')

# 初始化Django
django.setup()

# 现在可以导入Django模型了
from apps.tasks.models import Tasks


def insert_test_data():
    """插入100条测试数据"""
    print("开始插入数据...")
    
    # 定义一些可能的数据值
    epic_names = ['项目规划', '系统开发', '测试阶段', '上线部署', '维护阶段']
    story_names = ['用户管理功能', '数据统计模块', '报表生成功能', '系统配置', '权限管理']
    task_types = ['开发', '测试', '设计', '文档', '部署']
    projects = ['WMS系统', 'CRM系统', 'ERP系统', 'OA系统', 'BI系统']
    versions = ['v1.0', 'v1.1', 'v1.2', 'v2.0', 'v2.1']
    product_managers = ['张三', '李四', '王五', '赵六', '钱七']
    statuses = ['待开始', '进行中', '已完成', '已暂停', '已取消']
    responsible_persons = ['开发者A', '开发者B', '开发者C', '开发者D', '开发者E']
    
    # 生成当前日期
    today = datetime.now().date()
    
    tasks_to_create = []
    
    for i in range(100):
        # 生成唯一的task_id
        task_id = f'TASK{i:03d}'
        
        # 随机生成计划开始和结束日期
        start_days = random.randint(0, 30)
        end_days = random.randint(start_days + 1, start_days + 15)
        plan_start_time = today + timedelta(days=start_days)
        plan_end_time = today + timedelta(days=end_days)
        
        # 随机生成实际开始和结束日期（字符串格式）
        actual_start_time = plan_start_time.strftime('%Y-%m-%d') if random.choice([True, False]) else None
        actual_end_time = plan_end_time.strftime('%Y-%m-%d') if actual_start_time and random.choice([True, False]) else None
        
        # 创建任务对象
        task = Tasks(
            epic_name=random.choice(epic_names),
            story_name=random.choice(story_names),
            task_id=task_id,
            task_name=f'任务{i+1}: {random.choice(story_names)} - {random.choice(task_types)}',
            task_type=random.choice(task_types),
            project=random.choice(projects),
            fc_publish_version=random.choice(versions),
            product_manager=random.choice(product_managers),
            status=random.choice(statuses),
            fc_responsible_person=random.choice(responsible_persons),
            estimate_time=round(random.uniform(1.0, 10.0), 2),
            fc_plan_start_time=plan_start_time,
            fc_plan_end_time=plan_end_time,
            fc_actual_start_time=actual_start_time,
            fc_actual_end_time=actual_end_time
        )
        tasks_to_create.append(task)
    
    # 批量创建数据
    Tasks.objects.bulk_create(tasks_to_create)
    
    print(f"成功插入{len(tasks_to_create)}条数据到tasks表！")


if __name__ == '__main__':
    try:
        insert_test_data()
    except Exception as e:
        print(f"插入数据失败: {e}")
        sys.exit(1)